import plupload from 'plupload'
import { getUploadOssAPI } from '@/api/common'

export default {
  data () {
    return {
      // uploaderInstance: undefined,
      ossSignatureInfo: {},
      multipartParams: {
        'key': '',
        'policy': '',
        'OSSAccessKeyId': '',
        'success_action_status': '200', // 让服务端返回200,不然，默认会返回204
        'signature': ''
      },
      'expire': 0, // 过期时间戳
      'nowTimestamp': Date.parse(new Date()) / 1000 // 当前时间戳
    }
  },
  methods: {
    async getOssSignatureData () { // 获取Oss信息
      try {
        let response = await getUploadOssAPI()
        let result = response.data
        if (response.status > 199 && response.status < 300) {
          this.ossSignatureInfo = result
          this.expire = this.ossSignatureInfo['expire']
        } else {
          throw new Error('获取oss失败！')
        }
      } catch (error) {
        console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        })
      }
    },
    async setUploadParam (up) {
      this.nowTimestamp = Date.parse(new Date()) / 1000 // 更新当前时间
      if (this.expire < this.nowTimestamp) {
        await this.getOssSignatureData()
      }
      // this.multipartParams['key'] = this.ossSignatureInfo['dir'] + filename
      this.multipartParams['policy'] = this.ossSignatureInfo['policy']
      this.multipartParams['OSSAccessKeyId'] = this.ossSignatureInfo['accessid']
      this.multipartParams['signature'] = this.ossSignatureInfo['signature']
      up.setOption({
        'url': this.ossSignatureInfo['host']
      })
    },
    async initPlupload (container, selectfiles, multiSelection = false) { // 初始化plupload
      let _this = this
      let instance = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: selectfiles,
        url: '',
        multipart_params: {},
        chunk_size: '1mb',
        unique_names: true,
        container: document.getElementById(container),
        filters: {
          max_file_size: '10mb',
          mime_types: [
            { title: 'Image files', extensions: 'jpg,gif,png,jpeg' }
          ],
          prevent_duplicates: true // 不允许选取重复文件
        },
        multi_selection: multiSelection, // 是否多选 默认单选
        flash_swf_url: '../assets/js/lib/plupload-2.1.2/js/Moxie.swf',
        silverlight_xap_url: '../assets/js/lib/plupload-2.1.2/js/Moxie.xap',
        init: {
          PostInit (up) { // 当Init事件发生后触发监听函数参数：(uploader)
            // console.log(up)
            _this.setUploadParam(up)
          },

          FilesAdded (up, files) { // 当文件添加到上传队列后触发监听函数参数：(uploader,files)
            // console.log(up)
            up.start()
          },

          BeforeUpload (up, file) {
            // console.log(file)
            _this.multipartParams['key'] = _this.ossSignatureInfo['dir'] + file.id
            up.setOption({
              'multipart_params': _this.multipartParams
            })
          },

          UploadProgress (up, file) { // 会在文件上传过程中不断触发，可以用此事件来显示上传进度监听函数参数：(uploader,file)
            // console.log(file.percent)
          },

          FileUploaded (up, file, info) { // 当队列中的某一个文件上传完成后触发监听函数参数：(uploader,file,responseObject)
            _this.setUploadParam(up)
            // console.log(info)
            if (info.status >= 200 || info.status < 200) {
              // console.log(up)
              up.trigger('handleAddFile', file)
            } else {
              console.log(info.response)
            }
          },

          Error (up, err) { // 当发生错误时触发监听函数参数：(uploader,errObject)
            // console.log(up.removeFile())
            _this.setUploadParam(up)
            up.removeFile(err.file)
            // console.log(err)
            switch (err.code) {
              case -600:
                _this.$notify.error({
                  title: '错误',
                  message: '选择的文件太大!'
                })
                break
              case -601:
                _this.$notify.error({
                  title: '错误',
                  message: '选择的文件类型不符合要求!'
                })
                break
              case -602:
                _this.$notify.error({
                  title: '错误',
                  message: '选取了重复的文件!'
                })
                break
              default:
                _this.$notify.error({
                  title: '错误',
                  message: '上传失败!'
                })
                // up.removeFile(err.file)
                break
            }
          }
        }
      })

      return new Promise((resolve, reject) => {
        if (instance) {
          resolve(instance)
        } else {
          throw new Error('plupload初始化出错！')
        }
      })
    }
  }
}
